import static java.lang.System.out;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Setting extends JFrame implements ChangeListener, ActionListener {
	private static final int _MIN = 0;
	private static final int _MAX = 30;
	private int _INIT;
	private JPanel setPanel;
	private JLabel setSense;
	private JLabel description;
	private JSlider sense;
	private JButton ok;
	private JButton apply;
	private JButton cancel;
	private String appName = "Mobile Control - Setting";
	private BufferedImage appIcon;
	private int newSense;
	private PcClient client;
	
	public Setting(int curSen, PcClient client){
		try{
			appIcon = ImageIO.read(this.getClass().getResource("app_icon.jpg"));
		}
		catch(Exception e){
			e.printStackTrace();
		}
		_INIT = curSen;
		this.newSense = curSen;
		this.client = client;
		createPanel();
		this.setIconImage(appIcon);
		this.setTitle(appName);
		this.setUndecorated(false);
		this.setSize(250, 150);
		this.setLocationRelativeTo(null);
		this.add(setPanel);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	
	public void createPanel(){
		setPanel = new JPanel();
		setSense = new JLabel("Scale: ");
		description = new JLabel(_INIT+" pixels / per move.");
		sense = new JSlider(JSlider.HORIZONTAL, _MIN, _MAX, _INIT);
		sense.addChangeListener(this);
		ok = new JButton("OK");
		ok.setPreferredSize(new Dimension(70,20));
		ok.addActionListener(this);
		apply = new JButton("Apply");
		apply.setPreferredSize(new Dimension(70,20));
		apply.addActionListener(this);
		cancel = new JButton("Cancel");
		cancel.setPreferredSize(new Dimension(70,20));
		cancel.addActionListener(this);
		
		setPanel.add(setSense, BorderLayout.CENTER);
		setPanel.add(description);
		setPanel.add(sense, BorderLayout.SOUTH);
		setPanel.add(ok, BorderLayout.SOUTH);
		setPanel.add(apply);
		setPanel.add(cancel);
	}
	
	public int getScale(){
		return newSense;
	}
	
	@Override
	public void stateChanged(ChangeEvent e) {
		// TODO Auto-generated method stub
		JSlider source = (JSlider)e.getSource();
	    if (source == sense) {
	        int sen = (int)source.getValue();
	        this.newSense = sen;
	        description.setText(sen+" pixels / per move.");
	    }
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource()==ok){
			client.setScale(this.newSense);
			this.setVisible(false);
			this.dispose();
		}
		else if(e.getSource()==apply){
			client.setScale(this.newSense);
		}
		else if(e.getSource()==cancel){
			client.setScale(this._INIT);
			this.setVisible(false);
			this.dispose();
		}
		else{
			client.setScale(this._INIT);
			this.setVisible(false);
			this.dispose();
		}
	}
}
